package dmsxl.shuzu;

import java.util.Arrays;

/**
 * Author: Zhang Dongwei
 * Date: 2023/4/6 21:55
 */
public class array6_59 {

    public static void main(String[] args) {
        int n = 5;
        int[][] res = generateMatrix(n);
        for (int i=0; i<res.length; i++)
            System.out.println(Arrays.toString(res[i]));
    }

    public static int[][] generateMatrix1(int n) {
        int[][] res = new int[n][n];
        int l=0, r=n-1, t=0, b=n-1;
        int num=1, tar=n*n;
        while (num<=tar){
            for (int i=l; i<=r; i++) res[t][i] = num++;
            t++;
            for (int i=t; i<=b; i++) res[i][r] = num++;
            r--;
            for (int i=r; i>=l; i--) res[b][i] = num++;
            b--;
            for (int i=b; i>=t; i--) res[i][l] = num++;
            l++;
        }
        return res;
    }

    public static int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int l=0, t=0, r=n-1, b=n-1;
        int num=1, tar=n*n;
        while (num<=tar){
            for (int i=l; i<=r; i++) res[t][i]=num++;
            t++;
            for (int i=t; i<=b; i++) res[i][r]=num++;
            r--;
            for (int i=r; i>=l; i--) res[b][i]=num++;
            b--;
            for (int i=b; i>=t; i--) res[i][l]=num++;
            l++;
        }
        return res;
    }
}
